Page({
  data: {
    messages: [
      { type: 'ai', content: '👋 你好呀，我是 通义千问，很高兴认识你！🍃 此刻你在想些什么？有问题欢迎随时向我提问，或者把你想要知道的 🖥 知识发给我试试～' }
    ],
    inputVal: '',
    socketOpen: false,
    socketMsgQueue: []
  },

  onLoad: function() {
    this.scrollToBottom();
    this.connectWebSocket();
  },

  connectWebSocket: function() {
    const self = this;
    wx.connectSocket({
      url: 'ws://172.20.10.3:8084/chat',

      success() {
        self.setData({ socketOpen: true });
        self.flushSocketMsgQueue();
      }
    });

    wx.onSocketMessage(function(res) {
      const lastMessageIndex = self.data.messages.length - 1;
      const lastMessage = self.data.messages[lastMessageIndex];

      if (lastMessage.type === 'ai') {
        self.data.messages[lastMessageIndex].content += res.data;
      } else {
        const newMessages = self.data.messages.concat({ type: 'ai', content: res.data });
        self.setData({ messages: newMessages });
      }

      self.setData({ messages: self.data.messages });
      self.scrollToBottom();
    });

    wx.onSocketClose(function() {
      self.setData({ socketOpen: false });
    });

    wx.onSocketError(function() {
      self.setData({ socketOpen: false });
    });
  },

  flushSocketMsgQueue: function() {
    if (this.data.socketOpen && this.data.socketMsgQueue.length > 0) {
      this.data.socketMsgQueue.forEach(msg => {
        this.sendSocketMessage(msg);
      });
      this.setData({ socketMsgQueue: [] });
    }
  },

  sendSocketMessage: function(msg) {
    if (this.data.socketOpen) {
      wx.sendSocketMessage({
        data: msg
      });
    } else {
      this.data.socketMsgQueue.push(msg);
    }
  },

  bindInput: function(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },

  sendMessage: function() {
    const message = this.data.inputVal;
    if (message.trim() === '') return;

    this.setData({
      messages: [...this.data.messages, { type: 'user', content: message }],
      inputVal: ''
    });

    this.sendSocketMessage(message);
  },

  scrollToBottom: function() {
    wx.createSelectorQuery().select('#chatBox').boundingClientRect(function(rect) {
      wx.pageScrollTo({
        scrollTop: rect.bottom
      });
    }).exec();
  }
});
